{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "_llm = ChatOpenAI(\n",
    "    api_key=\"ollama\",\n",
    "    model=\"qwen2.5:7b\",\n",
    "    base_url=\"http://192.168.10.13:60001/v1\",\n",
    "    # temperature=0.7\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='好的，我会记录下来，称呼您张三。需要帮您Remember something else or do anything specific?比如，我可以帮助查询信息、提供建议或者进行其他对话。有什么可以帮忙的吗？', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 45, 'prompt_tokens': 35, 'total_tokens': 80}, 'model_name': 'qwen2.5:7b', 'system_fingerprint': 'fp_ollama', 'finish_reason': 'stop', 'logprobs': None}, id='run-961b0dfb-fa25-4c0e-b41b-68a8277611cc-0', usage_metadata={'input_tokens': 35, 'output_tokens': 45, 'total_tokens': 80})"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# _llm.invoke(\"记住我叫张三！\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='您是谁由您自行决定！在我们的对话中，您可以扮演任何角色或想象自己在任何情境当中。如果您有具体的身份或是情景设定，可以和我分享，那么我可以更好地与您进行互动和交流。比如：您可以在故事中是一位探险家、魔法师或者是普通人，都可以告诉我，让我们一起展开想象的翅膀。如果您没有设定特殊身份，那我想您可以是一个普通的用户，使用这个对话来了解我的能力和特点。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 94, 'prompt_tokens': 32, 'total_tokens': 126}, 'model_name': 'qwen2.5:7b', 'system_fingerprint': 'fp_ollama', 'finish_reason': 'stop', 'logprobs': None}, id='run-7fce92e8-75e7-4416-8630-437b4d29a2b9-0', usage_metadata={'input_tokens': 32, 'output_tokens': 94, 'total_tokens': 126})"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# _llm.invoke(\"我是谁？\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='您说自己是张三。如果您有任何问题或需要帮助，请随时告诉我！', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 17, 'prompt_tokens': 61, 'total_tokens': 78}, 'model_name': 'qwen2.5:7b', 'system_fingerprint': 'fp_ollama', 'finish_reason': 'stop', 'logprobs': None}, id='run-4432cae8-9c26-4a84-bbfc-c01d9fd761ba-0', usage_metadata={'input_tokens': 61, 'output_tokens': 17, 'total_tokens': 78})"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# from langchain_core.messages import HumanMessage\n",
    "\n",
    "# store=[\n",
    "#     HumanMessage(\"记住我叫张三！\")\n",
    "# ]\n",
    "\n",
    "# rep = _llm.invoke(store)\n",
    "# store.append(rep)\n",
    "# store.append(HumanMessage(\"我是谁\"))\n",
    "# rep = _llm.invoke(store)\n",
    "# rep"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.chat_message_histories import ChatMessageHistory\n",
    "\n",
    "_store = {}\n",
    "def get_session_history(session_id):\n",
    "    if session_id not in _store:\n",
    "        _store[session_id] = ChatMessageHistory()\n",
    "    return _store[session_id]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate,MessagesPlaceholder\n",
    "\n",
    "_messages = ChatPromptTemplate([\n",
    "    (\"system\",\"请用中文帮助用户\"),\n",
    "    MessagesPlaceholder(variable_name=\"history_contents\"),\n",
    "    (\"human\",\"{content}\")\n",
    "])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.output_parsers import StrOutputParser\n",
    "\n",
    "_chain = _messages|_llm|StrOutputParser()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "好的，您已成功记忆，您可以叫我张三。不过更纠正的话，应该是您叫我“张先生”或直接称呼您的名字才比较恰当。如果您有任何问题或者需要我的帮助，请随时告诉我。\n"
     ]
    }
   ],
   "source": [
    "from langchain_core.runnables import RunnableWithMessageHistory\n",
    "\n",
    "_his_chain = RunnableWithMessageHistory(\n",
    "    _chain,\n",
    "    get_session_history,\n",
    "    input_messages_key=\"content\",\n",
    "    history_messages_key=\"history_contents\"\n",
    ")\n",
    "\n",
    "rep01 = _his_chain.invoke({\"content\":\"记住我叫张三\"},config={\"configurable\":{\"session_id\":\"1\"}})\n",
    "print(rep01)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "您好，您之前提到您的名字是张三。如果您有任何其他问题或需要帮助，请告知我。\n"
     ]
    }
   ],
   "source": [
    "rep02 = _his_chain.invoke({\"content\":\"我叫什么名字\"},config={\"configurable\":{\"session_id\":\"1\"}})\n",
    "print(rep02)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "您自己也没有告诉我您的名字，所以我无法直接说出您的名字哦。请问您愿意告诉我是谁吗？\n"
     ]
    }
   ],
   "source": [
    "rep03 = _his_chain.invoke({\"content\":\"我叫什么名字\"},config={\"configurable\":{\"session_id\":\"2\"}})\n",
    "print(rep03)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py310",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
